#!/bin/bash
function install_jenkins() {
    echo -e "${blue}当前正在执行的操作为:${nocolor} ${green}安装Jenkins${nocolor}"
    echo ""
    jenkinsoPid=`ps aux|grep jenkins.war|grep java|grep -v grep|awk '{print $2}'`
    if [ -n "$jenkinsoPid" ];then
        echo -e "$Error 系统已经存在正在运行的Jenkins请停止并卸载后继续！"
        anykeyback
        return 1
    fi
    echo -ne "${blue}请确认已安装JDK，JDK要求${nocolor}
--------------------------------
| Jenkins版本        | JDK版本 |
--------------------------------
| 2.164及后续版本：  | Java 8+ |
| 2.54 及后续版本:   | Java 8  |
| 1.612及后续版本:   | Java 7  |
--------------------------------
已知悉。继续[Yy,Enter],退出[Nn]: "
    read isYn
    [[ $isYn != [Nn] ]] || { sleep 0.5;return 1; }
    echo ""
    
    echo -ne "${blue}Jenkins版本推荐${nocolor}
* 2.46.3      需要JAVA 7，此为支持JDK7的最后一个稳定版本
* 2.222.3     需要JAVA 8，此为目前为止最新的稳定版本
"
echo ""

    jenkinsVer=
    jenkins_dot=
    jenkins_digit=
    jenkins_endwith=
    while [[ ! $jenkins_digit =~ ^[0-9]+$ || "$jenkins_dot" == "0" || "$jenkins_endwith" == "." ]]
    do
        echo -ne "请输入Jenkins版本[2.222.3]，列出推荐版本HhTt[行数]，稳定版[Hh]每周版[Tt]: "
        read jenkinsVer
        jenkinsVer=${jenkinsVer:-2.222.3}
        jenkinsVer=`echo $jenkinsVer`
        jenkins_dot=$(echo $jenkinsVer|grep -o "\."|wc -l)
        jenkins_digit=$(echo $jenkinsVer|sed 's/\.//g')
        jenkins_endwith=${jenkinsVer:0-1}
        jenkinsVer_pre=${jenkinsVer:0:1}
        if [[  $jenkinsVer_pre == [HhTt] ]];then
            show_lines=$(echo $jenkinsVer|egrep -o "[0-9]*"|head -n 1)
            if [ "X$show_lines" == "X" ];then
                show_lines=100
            fi
            if [ "$die_network" == "ture" ];then
                    echo -e "$Info 设备未联网，不支持查询"
            else
                if [ "${jenkinsVer_pre^^}" == "H" ];then
                    curl -so $workHome/logs/jenkins-lts-rss.xml https://repo.huaweicloud.com/jenkins/redhat-stable/
                    cat $workHome/logs/jenkins-lts-rss.xml|egrep -o ">jenkins-.*rpm</a>"|awk -F"-" '{print $2}'|sort -rV|head -n $show_lines
                else
                    curl -so $workHome/logs/jenkins-week-rss.xml https://repo.huaweicloud.com/jenkins/redhat/
                    cat $workHome/logs/jenkins-week-rss.xml|egrep -o ">jenkins-.*rpm</a>"|awk -F"-" '{print $2}'|sort -rV|head -n $show_lines
                fi
            fi
        else
            if [[ ! $jenkins_digit =~ ^[0-9]+$ || "$jenkins_dot" == "0" ||${jenkins_dot} -gt 2 || "$jenkins_endwith" == "." ]];then
                echo -e "$Warn jenkins版本号只能由数字和.组成，且不以.结尾，请重新输入！"
                sleep 0.5
            fi
        fi
    done

    jenkinsPack="jenkins-$jenkinsVer-1.1.noarch.rpm"
    echo ""
    
    echo -ne "请输入Jenkins HOME目录[/var/lib/jenkins]: "
    read -e jenkinsPath
    jenkinsPath=${jenkinsPath:-/var/lib/jenkins}
    jenkinsPath=`echo $jenkinsPath`
    jenkinsPath=${jenkinsPath%/}
    echo ""
    
    isNull=`ls $jenkinsPath/* 2>/dev/null | wc -l`
    if [[ $isNull -gt 0 ]];then
        echo -ne "$Warn 目录非空，继续安装会删除已有数据！\n继续[Yy,Enter],退出[Nn]: "
        read isYn
        [[ $isYn != [Nn] ]] && echo "" || { sleep 0.5;return 1; }
    fi
    
    command -v ss >/dev/null 2>&1
    if [ "$?" == "0" ];then
        listen_cmd="ss -lnpt"
    else
        command -v netstat >/dev/null 2>&1
        if [ "$?" == "0" ];then
          listen_cmd="netstat -tnlp"
        fi
    fi
    [[ $listen_cmd ]] && PortCheck=Yes || PortCheck=No
    PortUsed=
    PortUsed_Pro=
    jenkinsPort=
    while [[ ! "$jenkinsPort" =~ ^[1-9][0-9]+$ || "$PortUsed" == "Yes" ]]
    do
        echo -ne "请输入Jenkins监听端口[8080]: "
        read jenkinsPort
        jenkinsPort=${jenkinsPort:-8080}
        jenkinsPort=`echo $jenkinsPort`
        if [[ ! "$jenkinsPort" =~ ^[1-9][0-9]+$ ]];then
             echo -e "$Warn jenkins端口只能为两位及以上的且不以0开头的数字组成，请重新输入！"
             sleep 0.3
        else
            if [ "$PortCheck" == "Yes" ];then
                PortUsed_Pro=`$listen_cmd 2>/dev/null |grep ":${jenkinsPort} "`
                if [ -n "$PortUsed_Pro" ];then
                  PortUsed=Yes
                  echo -e "$Warn Jenkins监听端口已被使用，请重新输入！"
                else
                  PortUsed=No
                fi
            else
                PortUsed=No
            fi
        fi
    done
    echo ""

    source /etc/profile >/dev/null 2>&1
    source ~/.bash_profile >/dev/null 2>&1
    source ~/.bashrc >/dev/null 2>&1
    javaPath=`command -v java`
    if [ -z "$javaPath" ];then
        echo -ne "未找到到java命令，请输入java命令路径: "
        read -e javaPath
    else
        echo -ne "检测到java命令路径为$javaPath\n确认[Yy,Enter],修改[Mm]: "
        read isMm
        if [[ $isMm == [Mm] ]];then
          echo -ne "请输入java命令位置: "
          read -e javaPath
        fi
    fi
    javaPath=`echo $javaPath`
    echo ""
    
    javaOut=`$javaPath -version 2>&1|grep 'version "'`
    if [ -z "$javaOut" ];then
        echo -e "$Error java命令不存在或者不可执行，退出Jenkins安装！"
        anykeyback
        return 1
    else
        java_main_version=`$javaPath -version 2>&1|grep 'version "'|awk -F"." '{print $2}'`
        jenkinsVer_main=${jenkinsVer%.*}
        if [ "${#jenkinsVer_main}" == "3" ];then
          jenkinsVer_1=${jenkinsVer_main//./00}
        elif [ "${#jenkinsVer_main}" == "4" ];then
          jenkinsVer_1=${jenkinsVer_main//./0}
        else
          jenkinsVer_1=${jenkinsVer_main//./}
        fi

        if [[ $jenkinsVer_1 -ge 2054 && $java_main_version -lt 8 ]];then
          echo -ne "要安装的Jenkins版本需要JDK8及以上版本\n继续[Yy,Enter],退出[Nn]: "
          read isYn
          [[ $isYn != [Nn] ]] && echo "" || { sleep 0.5;return 1; }
        fi
        if [[ $jenkinsVer_1 -lt 2054 && $jenkinsVer_1 -ge 1612 && $java_main_version -lt 7 ]];then
          echo -ne "要安装的Jenkins版本需要JDK7版本\n继续[Yy,Enter],退出[Nn]: "
          [[ $isYn != [Nn] ]] && echo "" || { sleep 0.5;return 1; }
        fi
    fi
    
    # java版本信息
    java_version=$($javaPath -version 2>&1|head -n 1)
    echo -ne "${blue}Jenkins安装信息汇总${nocolor}
--------------------------------------
Jenkins版本：$jenkinsVer
Jenkins路径：$jenkinsPath
Jenkins端口：$jenkinsPort
JAVA命令：$javaPath
JDK版本信息：$java_version
--------------------------------------
继续[Yy,Enter],退出[Nn]: "
    read isYn
    [[ $isYn != [Nn] ]] && echo "" || { sleep 0.5;return 1; }
    
    echo -e "${cyan}将开始Jenkins安装过程${nocolor}"
    if [ "$die_network" == "true" ];then
        ping -c 2 -w 5 180.76.76.76 >/dev/null 2>&1
        if [ "$?" != "0" ];then
           die_network="true"
        else
           die_network="false"
        fi
    fi
    jenkinsHome="$workHome/packages/jenkins"
    cd $jenkinsHome
    if [[ ! -f $jenkinsHome/$jenkinsPack && "$die_network" == "false" ]];then
        echo ""
        echo -e "$Info ${purple}下载jenkins安装包${nocolor}"
        
        if [ ${jenkins_dot} -eq 2 ];then
          iSstable="redhat-stable"
        else
          iSstable="redhat"
        fi
        
        echo -e "$Info ${purple}从华为云下载jenkins${nocolor}"
        curl --progress-bar --connect-timeout 30 -m 600 -O --fail https://mirrors.huaweicloud.com/jenkins/$iSstable/$jenkinsPack
        if [ "$?" != "0" ];then
          echo -e "$Info ${purple}从官网下载jenkins${nocolor}"
          curl --progress-bar --connect-timeout 30 -m 600 -O --fail http://archives.jenkins-ci.org/$iSstable/$jenkinsPack
        fi
        if [ "$?" != "0" ];then
          echo "$Info ${purple}从清华大学镜像站下载jenkins${nocolor}"
          curl --progress-bar --connect-timeout 30 -m 600 -O --fail https://mirrors.tuna.tsinghua.edu.cn/jenkins/$iSstable/$jenkinsPack
        fi
        if [ "$?" != "0" ];then
           echo -e "$Error 下载安装包失败，请检查网络或者是否存在此版本的Jenkins"
           anykeyback
           return 1
        fi
    elif [[ ! -f $jenkinsHome/$jenkinsPack && "$die_network" == "true" ]];then
        echo -e "$Error 你的主机未联网，请提前手动下载安装包，使用离线安装！！！"
        anykeyback
        return 1
    fi
    echo ""
    
    echo -e "$Info ${purple}卸载之前安装的Jenkins${nocolor}"
    yum -y remove jenkins
    rm -rf /var/log/jenkins
    rm -rf /usr/lib/jenkins
    rm -rf /var/cache/jenkins
    rm -rf $jenkinsPath
    echo ""
    
    echo -e "$Info ${purple}安装Jenkins依赖软件${nocolor}"
    yum -y install epel-release
    yum -y install fontconfig daemonize
    
    echo -e "$Info ${purple}开始安装Jenkins${nocolor}"
    rpm -ivh $jenkinsPack
    if [ "$?" != "0" ];then
        echo -e "$Error 安装失败，检查RPM包是否完整！"
        anykeyback
        return 1
    fi
    isNull_d=`ls /var/lib/jenkins/* 2>/dev/null | wc -l`
    if [[ $isNull_d -eq 0 ]];then
        rm -rf /var/lib/jenkins/
    fi
    mkdir -p $jenkinsPath
    chown -R jenkins:jenkins $jenkinsPath
    echo ""
    
    echo -e "$Info ${purple}修改Jenkins配置${nocolor}"
    sed -i "s#^JENKINS_JAVA_CMD=.*#JENKINS_JAVA_CMD=\"$javaPath\"#g" /etc/sysconfig/jenkins
    sed -i 's/JENKINS_AJP_PORT=.*/JENKINS_AJP_PORT="-1"/g' /etc/sysconfig/jenkins
    sed -i "s#^JENKINS_HOME=.*#JENKINS_HOME=\"$jenkinsPath\"#g" /etc/sysconfig/jenkins
    sed -i "s#^JENKINS_PORT=.*#JENKINS_PORT=\"$jenkinsPort\"#g" /etc/sysconfig/jenkins
  
    echo -e "$Info ${purple}启动Jenkins${nocolor}"
    service jenkins restart
    echo -e "$Info ${purple}等待Jenkins启动中.....${nocolor}"
    n=1
    response_status=1
    updateCenter_update=No
    while [ ! -f $jenkinsPath/secrets/initialAdminPassword -o $response_status -ne 200 ]
    do
        if [ $n -lt 10 ];then
            w=00$n
        elif [ $n -ge 10 -a $n -lt 100 ];then
            w=0$n
        else
            w=$n
        fi
        printf "%s %-3s %s\r" "等待Jenkins启动" "$w/360" "s"
        let n+=1
        sleep 1
        if [ $n -gt 360 ];then
            break
        fi
        response_status=$(curl -I -m 10 -o /dev/null -s -w %{http_code} http://127.0.0.1:${jenkinsPort}/login)
        if [ -f $jenkinsPath/hudson.model.UpdateCenter.xml -a "${updateCenter_update}" == "No" ];then
            updateCenter="https://mirrors.tuna.tsinghua.edu.cn/jenkins/updates/update-center.json"
            #updateCenter="https://repo.huaweicloud.com/jenkins/updates/update-center.json"
            sed -i "s#http.*://.*update-center.json#$updateCenter#g" $jenkinsPath/hudson.model.UpdateCenter.xml
            updateCenter_update=Yes
        fi
    done
    
    echo ""
    sleep 2
    
    if [ $response_status -eq 200 ];then
        echo -e "$Info ${purple}Jenkins启动成功${nocolor}"
    else
        echo -e "$Warn ${purple}启动Jenkins超时${nocolor}"
    fi
    sleep 2
    
    echo -e "$Info ${purple}启用Jenkins插件安装镜像加速${nocolor}"
    if [ -f $jenkinsPath/updates/default.json ];then
        offical_url=$(cat $jenkinsPath/updates/default.json |sed 's#,"url":"#\n#g'|egrep -o \
        "https://updates\..*?/download/.*?\.hpi"|awk -F'/plugins' '{print $1}'|sort -u|head -n1)
        mirrors_url="https://mirrors.tuna.tsinghua.edu.cn/jenkins"
        #mirrors_url="https://repo.huaweicloud.com/jenkins"
        sed -i "s#${offical_url}#${mirrors_url}#g" $jenkinsPath/updates/default.json
        sed -i 's#http://www.google.com#https://www.baidu.com#g' $jenkinsPath/updates/default.json
        # sed -i 's#http://updates.jenkins-ci.org/download#https://mirrors.tuna.tsinghua.edu.cn/jenkins#g' $jenkinsPath/updates/default.json
        # sed -i 's#https://updates.jenkins.io/download#https://mirrors.tuna.tsinghua.edu.cn/jenkins#g' $jenkinsPath/updates/default.json
        echo -e "$Info ${purple}重启Jenkins以使配置生效${nocolor}"
        service jenkins restart
        echo -e "$Info ${purple}等待Jenkins重新启动中.....${nocolor}"
        n=1
        response_status=1
        while [ $response_status -ne 200 ]
        do
            if [ $n -lt 10 ];then
                w=00$n
            elif [ $n -ge 10 -a $n -lt 100 ];then
                w=0$n
            else
                w=$n
            fi
            printf "%s %-3s %s\r" "等待Jenkins配置生效" "$w/360" "s"
            let n+=1
            sleep 1
            if [ $n -gt 360 ];then
                break
            fi
            response_status=$(curl -I -m 10 -o /dev/null -s -w %{http_code} http://127.0.0.1:${jenkinsPort}/login)
        done
        echo -e "$Info ${purple}若重新获取了插件更新信息，则应参考说明以重新启用镜像加速${nocolor}"
    else
        echo -e "$Warn 未生成default.json文件，请参考说明手动启用jenkins插件镜像加速"
    fi
    echo ""
    
    if [ -f $jenkinsHome/jenkins-plugins-$jenkinsVer.zip ];then
        echo -e "$Info ${purple}加载Jenkins插件${nocolor}"
        rm -rf $jenkinsHome/jenkins-plugins
        mkdir $jenkinsHome/jenkins-plugins
        /bin/cp -f $jenkinsHome/jenkins-plugins-$jenkinsVer.zip $jenkinsHome/jenkins-plugins
        cd $jenkinsHome/jenkins-plugins
        unzip jenkins-plugins-$jenkinsVer.zip 2>&1
        #停止jenkins
        service jenkins stop
        find . -name "*.jpi" -type f -exec /bin/mv -f {} $jenkinsPath/plugins/ \;
        find . -name "*.hpi" -type f -exec /bin/mv -f {} $jenkinsPath/plugins/ \;
        cd $jenkinsHome
        rm -rf jenkins-plugins
        echo -e "$Info ${purple}重新启动Jenkins${nocolor}"
        service jenkins restart
        echo -e "$Info ${purple}等待Jenkins重启中.....${nocolor}"
        i=1
        while [ -f $jenkinsPath/queue.xml ]
        do
           echo "等待jenkins重启 $i"
           let i+=1
           sleep 1
           if [ $i -gt 20 ];then
               jenkinsPidr=`ps aux|grep jenkins.war|grep java|grep -v grep|awk '{print $2}'`
               [[ -z "$jenkinsPidr" ]] && break
           fi        
           if [ $i -gt 50 ];then
                break
           fi
        done
    fi

    #判断是否启动
    echo ""
    if [ ! -f $jenkinsPath/secrets/initialAdminPassword ];then
        passwd_tip="初始密码位于：$jenkinsPath/secrets/initialAdminPassword"
    else
        jenkins_init_pw=`cat $jenkinsPath/secrets/initialAdminPassword 2>>$logs_file`
        passwd_tip="初始密码为：$jenkins_init_pw"
    fi
    jenkinsPid=`ps aux|grep jenkins.war|grep java|grep -v grep|awk '{print $2}'`
    if [ -n "$jenkinsPid" -a -f $jenkinsPath/config.xml ];then
        echo -e "$Info ${light_green}Jenkins $jenkinsVer安装成功${nocolor}
--------------------------------------------
访问地址：http://$ipaddr:$jenkinsPort
${passwd_tip}
数据文件位置：$jenkinsPath
日志文件：/var/log/jenkins
--------------------------------------------"
    else
        echo -e "$Error Jenkins $jenkinsVer安装失败！！！\n请使用service jenkins status以及日志文件排查错误"
    fi
    echo ""
    anykeyback
}